package com.vcms.view.simulation.storemanagement;

// Copyright 1997 ISS.
// The contents contained in this document may not be reproduced in any
// form or by any means, without the written permission of ISS, other
// than for the purpose for which it has been supplied.
//
// Author: Olivo Miotto
//

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;

import com.vcms.controller.storemanagement.StoreController;
import com.vcms.entity.store.item.StoreItem;
import com.vcms.entity.store.itemtype.StoreObject;
import com.vcms.exception.VMCSException;
import com.vcms.view.simulation.uicomponent.display.LabelledDisplay;
import com.vcms.view.simulation.uicomponent.listener.StoreViewerListener;

@SuppressWarnings("serial")
public class StoreViewer extends Panel {

	private LabelledDisplay viewItems[];
	private StoreController storeCtrl;
	private char type;
	public static final String CASH_VIEW_TITLE = "Quantity of Coins Available";
	public static final String DRINK_VIEW_TITLE = "Quantity of Drinks Available";
	private int sSize; // store size;

	public StoreViewer(char ti, StoreController sctrl) {
		storeCtrl = sctrl;

		Label lb;

		type = ti;
		if (type == StoreController.CASH) {
			lb = new Label(CASH_VIEW_TITLE);
		} else {
			lb = new Label(DRINK_VIEW_TITLE);

		}
		lb.setFont(new Font("Helvetica", Font.BOLD, 12));

		sSize = storeCtrl.getStoreSize(type);

		Panel pl = new Panel(new FlowLayout(FlowLayout.LEFT));
		pl.add(lb);

		viewItems = new LabelledDisplay[sSize];

		StoreItem[] storeItem;
		storeItem = storeCtrl.getStoreItems(type);

		this.setLayout(new GridLayout(0, 1));

		this.add(pl);

		String name;
		String sval;
		int val;
		int i;

		StoreViewerListener svl;
		StoreObject ob;

		for (i = 0; i < sSize; i++) {
			ob = storeItem[i].getContent();
			name = ob.getName();
			val = storeItem[i].getQuantity();
			sval = String.valueOf(val);
			viewItems[i] = new LabelledDisplay(name, LabelledDisplay.DEFAULT,
					LabelledDisplay.GRID);
			viewItems[i].setValue(sval);
			svl = new StoreViewerListener(type, i, storeCtrl);
			viewItems[i].addListener(svl);
			this.add((Panel)viewItems[i].getLabelledDisplay());
		}
	}

	public void update() throws VMCSException {
		int size = this.storeCtrl.getStoreSize(this.type);
		for (int i = 0; i < size; i++) {
			if (i >= sSize)
				throw new VMCSException("StoreViewer.update", "index overflow");
			
			StoreItem item = this.storeCtrl.getStoreItem(this.type, i);
			viewItems[i].setValue(item.getQuantity());
		}
		
	}

	public void closeDown() {
	}

	public void setActive(boolean state) {
		this.setEnabled(state);
	}
}
